package com.example.download.service;

import com.example.download.entity.Database;
import com.example.download.enums.DatabaseEnum;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SendRequestService {

    public List<String> sendRequestS() throws Exception {
        ArrayList<String> strings = new ArrayList<>();
        for (DatabaseEnum value : DatabaseEnum.values()) {
            String s = sendRequest(value);
            strings.add(s);
        }
        return strings;
    }
    public String sendRequest(DatabaseEnum databaseEnum) throws Exception {
        // 创建一个LocalDateTime对象
        LocalDateTime now = LocalDateTime.now();
        boolean chengGong=true;
        // 创建一个DateTimeFormatter对象，指定日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // 将LocalDateTime对象转换为字符串
        String dateTimeString = now.format(formatter);
        String name = databaseEnum.getTableName() + "_" + dateTimeString + ".txt";
        String filePath = databaseEnum.getDeriveUrl() + name;

        try (Connection connection = DriverManager.getConnection(databaseEnum.getUrl(), databaseEnum.getUsername(), databaseEnum.getPassword());
             Statement statement = connection.createStatement()) {

//            // 检查用户是否有FILE权限，如果没有，则无法执行导出操作
//            ResultSet resultSet = statement.executeQuery("SHOW GRANTS FOR CURRENT_USER");
//            boolean hasFilePermission = false;
//            while (resultSet.next()) {
//                if (resultSet.getString(1).contains("FILE")) {
//                    hasFilePermission = true;
//                    break;
//                }
//            }
//
//            if (!hasFilePermission) {
//                System.out.println("Error: You do not have FILE permission.");
//                return null;
//            }
            // 执行SQL查询并将结果导出到CSV文件
            ResultSet rs = statement.executeQuery("SELECT * FROM "+databaseEnum.getTableName()+" INTO OUTFILE '" + filePath + "' " +
                    "FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n'");


            System.out.println("导出成功，文件： " + filePath + ".共行: " + rs);

            // 构建DROP TABLE语句
//            String sql = "DROP TABLE IF EXISTS " + databaseEnum.getTableName();
            String sql = "TRUNCATE TABLE " + databaseEnum.getTableName();

            // 执行SQL语句
            statement.executeUpdate(sql);
            System.out.println("删除： " + databaseEnum.getTableName() );

        } catch (SQLException e) {
            chengGong=false;
            System.err.format("SQL State: %s\n%s", e.getErrorCode(), e.getMessage());
        }
        if (chengGong){
            String downloadUrl=databaseEnum.getDownloadUrl()+name;

            String saveUrl= downloadFile(downloadUrl,databaseEnum.getSaveUrl(),name);

            removeDuplicateData(saveUrl);
            return name;
        }

        return null;
    }



    public String sendRequest(Database database) throws Exception {
        // 创建一个LocalDateTime对象
        LocalDateTime now = LocalDateTime.now();
        boolean chengGong=true;
        // 创建一个DateTimeFormatter对象，指定日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // 将LocalDateTime对象转换为字符串
        String dateTimeString = now.format(formatter);
        String name = database.getTableName() + "_" + dateTimeString + ".txt";
        String filePath = database.getDeriveUrl() + name;

        try (Connection connection = DriverManager.getConnection(database.getUrl(), database.getUsername(), database.getPassword());
             Statement statement = connection.createStatement()) {

//            // 检查用户是否有FILE权限，如果没有，则无法执行导出操作
//            ResultSet resultSet = statement.executeQuery("SHOW GRANTS FOR CURRENT_USER");
//            boolean hasFilePermission = false;
//            while (resultSet.next()) {
//                if (resultSet.getString(1).contains("FILE")) {
//                    hasFilePermission = true;
//                    break;
//                }
//            }
//
//            if (!hasFilePermission) {
//                System.out.println("Error: You do not have FILE permission.");
//                return null;
//            }
            // 执行SQL查询并将结果导出到CSV文件
            ResultSet rs = statement.executeQuery("SELECT * FROM "+database.getTableName()+" INTO OUTFILE '" + filePath + "' " +
                    "FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n'");


            System.out.println("导出成功，文件： " + filePath + ".共行: " + rs);

            // 构建DROP TABLE语句
//            String sql = "DROP TABLE IF EXISTS " + databaseEnum.getTableName();
            String sql = "TRUNCATE TABLE " + database.getTableName();

            // 执行SQL语句
            statement.executeUpdate(sql);
            System.out.println("删除： " + database.getTableName() );

        } catch (SQLException e) {
            chengGong=false;
            System.err.format("SQL State: %s\n%s", e.getErrorCode(), e.getMessage());
        }
        if (chengGong){
            String downloadUrl=database.getDownloadUrl()+name;

           String saveUrl= downloadFile(downloadUrl,database.getSaveUrl(),name);

            removeDuplicateData(saveUrl);
            return name;
        }

        return null;
    }


    public String downloadFile(String fileURL, String savePath, String name) {
        String  saveurl=savePath+name;

        try {
            Date date = new Date();
            long timestamp = date.getTime();
            System.out.println("当前时间戳（毫秒）: " + timestamp);

            System.out.println("开始下载:"+fileURL+" 保存到："+saveurl);
            // 创建URL对象
            URL url = new URL(fileURL);

            // 打开连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            // 设置超时时间
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setReadTimeout(5000);

            // 获取输入流
            InputStream inputStream = httpURLConnection.getInputStream();

            // 创建文件输出流

            // 检查路径是否存在

            if (Files.exists(Paths.get(saveurl))) {
                System.out.println("文件已存在: " + savePath);
                Instant now = Instant.now();
                long millis = now.toEpochMilli();
                saveurl  = saveurl.replace(".txt", "_" + millis + ".txt");
            }


            FileOutputStream fileOutputStream = new FileOutputStream(saveurl);

            // 读取输入流并写入文件输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流
            fileOutputStream.close();
            inputStream.close();

            // 断开连接
            httpURLConnection.disconnect();
            System.out.println("开始完成:"+saveurl+" 保存到："+savePath);
            System.out.println(name+"文件下载成功！");
//            removeDuplicateData(savePath);

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(name+"文件下载失败！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return saveurl;
    }

    public  void removeDuplicateData(String fileURL) throws Exception {
        try {


        String escaped = fileURL.replace("\\", "\\\\");


        String url = "http://localhost:9005/api/RawData/addRedisData";
        String jsonPayload = "[{\"type\": \"file\",\"name\": \"demoData\",\"location\": \""+escaped+"\"}]";

        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求体
        StringEntity entity = new StringEntity(jsonPayload, "UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json");

        // 执行请求
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();

        // 读取响应
        String responseString = EntityUtils.toString(responseEntity, "UTF-8");
        System.out.println(responseString);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("文件去重失败！");
        }
    }
}
